package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.feignapi.ArticleFeign;
import com.heima.feignapi.WemediaFeign;
import com.heima.model.article.dtos.AuthorDto;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.user.dtos.AuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserAuth;
import com.heima.user.mapper.ApUserAuthMapper;
import com.heima.user.service.ApUserAuthService;
import com.heima.user.service.ApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-05-25
 */
@Slf4j
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements ApUserAuthService {

    @Autowired
    private ApUserService userService;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    /**
     * 用户实名认证分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<ApUserAuth> pageQuery(AuthDto dto) {
        LambdaQueryWrapper<ApUserAuth> queryWrapper = new LambdaQueryWrapper<>();
        // 设置status参数
        queryWrapper.eq(dto.getStatus() != null, ApUserAuth::getStatus, dto.getStatus());
        // 设置分页参数
        Page<ApUserAuth> ipage = new Page<>(dto.getPage(), dto.getSize());
        // 分页查询
        Page<ApUserAuth> pageResponse = this.page(ipage, queryWrapper);
        return new PageResult(dto.getPage(), dto.getSize(), pageResponse.getTotal(), pageResponse.getRecords());
    }

    /**
     * 审核不通过
     *
     * @param dto
     */
    @Override
    public void authFail(AuthDto dto) {
        // 修改状态为审核失败，填充审核失败的信息
        ApUserAuth toBeUpdate = new ApUserAuth();
        toBeUpdate.setId(dto.getId());
        toBeUpdate.setReason(dto.getMsg());
        toBeUpdate.setUpdatedTime(new Date());
        toBeUpdate.setStatus(2);//TODO 改成枚举
        this.updateById(toBeUpdate);
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    public void authPass(AuthDto dto) {
        // 根据实名认证申请的id查询实名认证信息
        ApUserAuth userAuthDB = this.getById(dto.getId());
        //非空判断
        if (userAuthDB == null) {
            log.error("根据认证id查询不到认证信息， id：{}", dto.getId());
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //修改认证的状态 ap_user_auth
        updateApUserAuth(dto.getId());

        //修改用户的身份
        ApUser apUser = new ApUser();
        apUser.setId(userAuthDB.getId());
        apUser.setFlag(1);//TODO 枚举
        apUser.setIsCertification(true);
        apUser.setIsIdentityAuthentication(true);
        userService.updateById(apUser);
        log.info("--------------------->修改用户的身份");
        // 创建自媒体人 feign, wm_user
        // 根据user_id查询user数据
        ApUser apUserDB = userService.getById(userAuthDB.getId());
        if (apUserDB == null) {
            log.error("根据userid查询不到user信息， id：{}", userAuthDB.getUserId());
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUserDto wmUserDto = new WmUserDto();
        wmUserDto.setApUserId(apUserDB.getId());
        wmUserDto.setName(apUserDB.getName());
        wmUserDto.setPassword(apUserDB.getPassword());
        wmUserDto.setPhone(apUserDB.getPhone());
        wmUserDto.setStatus(9);//TODO 枚举
        int wmUserId = wemediaFeign.saveWmUser(wmUserDto);
        log.info("--------------------->创建自媒体人, wmUserId:{}", wmUserId);
        // 创建文章作者 feign, ap_author
        AuthorDto authorDto = new AuthorDto();
        authorDto.setName(userAuthDB.getName());
        authorDto.setUserId(userAuthDB.getId());
        authorDto.setWmUserId(wmUserId);
        authorDto.setType(2);// TODO 枚举
        int authorId = articleFeign.saveAuthor(authorDto);
        log.info("--------------------->创建文章作者 over, authorId:{}", authorId);
    }

    private void updateApUserAuth(Integer id) {
        ApUserAuth apUserAuth = new ApUserAuth();
        apUserAuth.setId(id);
        apUserAuth.setStatus(9);
        apUserAuth.setUpdatedTime(new Date());
        apUserAuth.setReason("");
        this.updateById(apUserAuth);
        log.info("--------------------->修改认证的状态");
    }
}
